package com.mayfool.gitmanager.ui.dialog;

import com.mayfool.gitmanager.core.entity.BranchDeleteResult;
import com.mayfool.gitmanager.core.entity.ProjectInfo;
import com.mayfool.gitmanager.core.entity.TaskInfo;
import com.mayfool.gitmanager.core.enums.BranchDeleteStatus;
import com.mayfool.gitmanager.core.helper.GitOperations;
import com.mayfool.gitmanager.core.helper.LogHelper;

import javax.swing.*;
import java.awt.*;
import java.io.File;

/**
 * 分支删除对话框
 * 
 * @author zhou.xu
 * @date 2024-03-18 17:00:00
 */
public class BranchDeleteDialog extends JDialog {
    private final TaskInfo task;
    private final GitOperations gitOps;
    private final String branchName;
    
    private JButton nextButton;
    private JButton cancelButton;
    
    private int currentStep = 0;

    public BranchDeleteDialog(Frame owner, TaskInfo task, GitOperations gitOps, String branchName) {
        super(owner, "删除分支确认", true);
        this.task = task;
        this.gitOps = gitOps;
        this.branchName = branchName;
        
        initComponents();
        setupLayout();
        processNextStep();
    }

    private void initComponents() {
        nextButton = new JButton("下一步");
        nextButton.addActionListener(e -> processNextStep());
        
        cancelButton = new JButton("取消");
        cancelButton.addActionListener(e -> dispose());
    }

    private void setupLayout() {
        setLayout(new BorderLayout());
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(cancelButton);
        buttonPanel.add(nextButton);
        add(buttonPanel, BorderLayout.SOUTH);
        
        // 设置对话框大小和位置
        setSize(400, 150);
        setLocationRelativeTo(getOwner());
    }

    private void processNextStep() {
        switch (currentStep) {
            case 0:
                // 第一步：检查所有项目的分支状态
                checkAllBranchStatus();
                break;
            case 1:
                // 第二步：删除本地分支
                deleteLocalBranches();
                break;
            case 2:
                // 第三步：确认是否删除远程分支
                confirmRemoteBranchDeletion();
                break;
            case 3:
                // 第四步：删除远程分支
                deleteRemoteBranches();
                break;
            default:
                dispose();
                break;
        }
        currentStep++;
    }

    private void checkAllBranchStatus() {
        LogHelper.getInstance().info("开始检查分支状态...");
        boolean hasValidBranch = false;
        boolean hasRemoteBranch = false;
        
        for (ProjectInfo project : task.getProjects()) {
            String projectPath = task.getWorkspacePath() + File.separator + project.getName();
            BranchDeleteResult result = gitOps.checkBranchStatus(projectPath, branchName);
            LogHelper.getInstance().info(String.format("[%s] %s: %s",
                project.getName(),
                result.getStatus().getMessage(),
                result.getErrorMessage() != null ? result.getErrorMessage() : ""));
            
            if (result.getStatus() == BranchDeleteStatus.SUCCESS) {
                hasValidBranch = true;
                if (result.hasRemoteBranch()) {
                    hasRemoteBranch = true;
                }
            }
        }
        
        if (!hasValidBranch) {
            LogHelper.getInstance().info("没有可以删除的分支，操作终止。");
            nextButton.setText("关闭");
            currentStep = 99; // 跳过后续步骤
        } else {
            LogHelper.getInstance().info(String.format("发现可删除的分支，%s存在远程分支。",
                hasRemoteBranch ? "部分项目" : "没有项目"));
            nextButton.setText("开始删除本地分支");
        }
    }

    private void deleteLocalBranches() {
        LogHelper.getInstance().info("开始删除本地分支...");
        boolean hasError = false;
        
        for (ProjectInfo project : task.getProjects()) {
            String projectPath = task.getWorkspacePath() + File.separator + project.getName();
            BranchDeleteResult result = gitOps.deleteLocalBranch(projectPath, branchName);
            if (result.getStatus() == BranchDeleteStatus.SUCCESS) {
                LogHelper.getInstance().info(String.format("[%s] 本地分支删除成功", project.getName()));
            } else {
                hasError = true;
                LogHelper.getInstance().error(String.format("[%s] 本地分支删除失败: %s",
                    project.getName(),
                    result.getErrorMessage() != null ? result.getErrorMessage() : result.getStatus().getMessage()));
            }
        }
        
        if (hasError) {
            LogHelper.getInstance().warn("部分项目删除本地分支失败。");
        } else {
            LogHelper.getInstance().info("所有本地分支删除完成。");
        }
        
        nextButton.setText("确认删除远程分支");
    }

    private void confirmRemoteBranchDeletion() {
        int confirm = JOptionPane.showConfirmDialog(
            this,
            String.format("是否删除远程分支 '%s'？", branchName),
            "删除远程分支确认",
            JOptionPane.YES_NO_OPTION,
            JOptionPane.WARNING_MESSAGE
        );
        
        if (confirm == JOptionPane.YES_OPTION) {
            LogHelper.getInstance().info("用户确认删除远程分支。");
            nextButton.setText("开始删除远程分支");
        } else {
            LogHelper.getInstance().info("用户取消删除远程分支，操作完成。");
            nextButton.setText("关闭");
            currentStep = 99; // 跳过后续步骤
        }
    }

    private void deleteRemoteBranches() {
        LogHelper.getInstance().info("开始删除远程分支...");
        boolean hasError = false;
        
        for (ProjectInfo project : task.getProjects()) {
            String projectPath = task.getWorkspacePath() + File.separator + project.getName();
            BranchDeleteResult result = gitOps.deleteRemoteBranch(projectPath, branchName);
            if (result.getStatus() == BranchDeleteStatus.SUCCESS) {
                LogHelper.getInstance().info(String.format("[%s] 远程分支删除成功", project.getName()));
            } else {
                hasError = true;
                LogHelper.getInstance().error(String.format("[%s] 远程分支删除失败: %s",
                    project.getName(),
                    result.getErrorMessage() != null ? result.getErrorMessage() : result.getStatus().getMessage()));
            }
        }
        
        if (hasError) {
            LogHelper.getInstance().warn("部分项目删除远程分支失败。");
        } else {
            LogHelper.getInstance().info("所有远程分支删除完成。");
        }
        
        nextButton.setText("关闭");
    }
} 